package com.tedu.controller;

import com.tedu.entity.Emp;
import com.tedu.service.impl.EmpServiceImpl;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "AddEmpServlet", value = "/emp/add")
public class AddEmpServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        //设置请求中文乱码处理
        request.setCharacterEncoding("utf-8");
        //获取请求参数
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String birthday = request.getParameter("birthday");
        String deptid = request.getParameter("deptId");
        String hiredate = request.getParameter("hiredate");
        System.out.println(name);
        System.out.println(salary);
        System.out.println(birthday);
        System.out.println(deptid);
        System.out.println(hiredate);
        //调用业务逻辑
        //创建对象
        try {
            Emp emp = new Emp();
            //将字符串转化为指定的日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthdayDate = sdf.parse(birthday);
            Date hiretime = sdf.parse(hiredate);
            //将字符串数字转为数字
            double sal = Double.parseDouble(salary);
            int id = Integer.parseInt(deptid);
            emp.setName(name).setBirthday(birthdayDate).setHiredate(hiretime).setDeptid(id).setSalary(sal);

            EmpServiceImpl empService = new EmpServiceImpl();
            empService.insertEmp(emp);


            response.sendRedirect(request.getContextPath()+"/emp/findAllEmp");

        } catch (Exception e) {
            e.printStackTrace();
            request.getRequestDispatcher("/ems/emp/addEmp.jsp").forward(request, response);
        }


    }
}
